<?php
/**
 * 信贷保镖接口调用
 * https://credit.tongdun.cn/creditbodyguard/bodyguard/bodyguardApi.htm?operationType=switchWorkFlowCode&workFlowCode=RealnaWeb
 *
 * 2018-02-27
 * 
 * @param mixed $bizcode [option] 
 * {
 *  'BbtWeb'=>'奔奔兔网页',
 *  'RealnaWeb'=>'实名认证网页',
 *  'PhthrWeb'=>'手机号三要素网页',
 *  'InnetWeb'=>'手机号在网时长网页',
 *  'FraudscWeb'=>'欺诈分二点零网页',
 *  'FamaddWeb'=>'家庭地址核验网页',
 *  'EmpaddWeb'=>'工作地址核验网页',
 *  'CrescWeb'=>'信用分网页',
 * }
 * 
 */

namespace Org\Util;

class Bodyguard 
{
	// 信贷保镖接口地址
	const API_URL        = 'https://api.tongdun.cn/bodyguard/apply/v4';
	// 合作方标识
	private $partnercode = 'bbtqc';
	// 合作方密钥
	private $partnerkey  = '';
	// 应用标识
	private $appname     = 'bbt_web';
	// 业务流
	public $bizcode      = ['BbtWeb','RealnaWeb','PhthrWeb','InnetWeb','FraudscWeb','FamaddWeb','EmpaddWeb','CrescWeb'];
	// api请求地址
	private $apiurl      = '';

	function __construct($bizcode=false)
	{
		if($bizcode) $this->bizcode = $bizcode;
		$this->partnerkey = C('TDPARTNERKEY');
		$this->apiurl = static::API_URL.'?'.http_build_query([
			'partner_code' => $this->partnercode,
			'partner_key'  => $this->partnerkey,
			'app_name'     => $this->appname,
		]);
	}

	/**
	 * 贷前反欺诈
	 * @param String $account_name 借款人姓名
	 * @param String $id_number 借款人身份证
	 * @param String $account_mobile 借款人手机
	 * @param String $dataType 返回数据类型
	 */
	public function antiFraud($account_name, $id_number, $account_mobile, $dataType=null)
	{
		if($this->bizcode!='BbtWeb'&&!in_array('BbtWeb', $this->bizcode)) return false;
		$fileName="UserBbtJson/".$account_mobile.'.json';
        $postRes=ossGetObject($fileName);
        if(!$postRes){
        	$postRes = $this->vpost($this->apiurl,http_build_query([
				'biz_code'      =>'BbtWeb',
				'account_name'  =>$account_name,
				'id_number'     =>$id_number,
				'account_mobile'=>$account_mobile
			]),$dataType);
			if(empty($postRes['reason_code'])){
				ossPutObject($fileName,json_encode($postRes,true));
			}
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 贷前反欺诈（过滤字段）
	 * @param String $account_name 借款人姓名
	 * @param String $id_number 借款人身份证
	 * @param String $account_mobile 借款人手机
	 */
	public function  antiFraudFilter($account_name, $id_number, $account_mobile) 
	{
		// 敏感关键词
		$check_str=[
			'身份证归属地位于高风险较为集中地区',
			'身份证命中法院失信名单',
			'身份证命中犯罪通缉名单',
			'身份证命中法院执行名单', 
			'身份证命中信贷逾期名单',
			'身份证命中高风险关注名单', 
			'身份证命中车辆租赁违约名单',
			'身份证命中法院结案名单', 
			'身份证_姓名命中信贷逾期模糊名单',
			'身份证_姓名命中法院失信模糊名单', 
			'身份证_姓名命中法院执行模糊名单', 
			'身份证_姓名命中法院结案模糊名单', 
			'身份证命中欠款公司法人代表名单',
			'身份证命中故意违章乘车名单',
			'身份证命中信贷逾期后还款名单',
			'手机号命中虚假号码库',
			'手机号命中诈骗骚扰库',
			'手机号命中高风险关注名单',
			'手机号命中信贷逾期名单',
			'手机号命中车辆租赁违约名单',
			'3个月内身份证关联多个申请信息',
			'3个月内申请信息关联多个身份证',
			'3个月内银行卡_姓名关联多个身份证',
			'3个月内申请人在多个平台申请借款',
			'3个月内申请人在多个平台被放款_不包含本合作方',
			'申请人信息命中中风险关注名单',
			'申请人信息命中低风险关注名单'
		];
		$resdata = $this->antiFraud($account_name, $id_number, $account_mobile,'array');
		if(!empty($resdata['reason_code'])){
			return ['success'=>true,'error'=>$resdata['reason_code'],'message'=>$resdata['reason_desc']];
		}
		$returnData = [];
		if($resdata['result_desc'] && $resdata['result_desc']['ANTIFRAUD'] && $resdata['result_desc']['ANTIFRAUD']['risk_items']){
            $risk_items=$resdata['result_desc']['ANTIFRAUD']['risk_items'];
            foreach($risk_items as $val){
                if(in_array($val['risk_name'],$check_str)){
                    $returnData[]=$val['risk_name']." ".$this->hitDetails($val['risk_name'],$val['risk_detail']);
                }
            }
        }
        if(empty($returnData)){
        	return ['success'=>true,'message'=>'该身份信息未匹配到风险项！（<font color="ForestGreen">安全</font>）'];
        }else{
        	return ['success'=>'1','data'=>$returnData];
        }
	}

	/**
	 * 将命中风险详情返回
	 */
	public function hitDetails($str,$hitdetails)
	{
		switch ($str) {
			case '身份证归属地位于高风险较为集中地区':
				$response = $hitdetails['description']."：<br />";
				for ($i=0; $i < count($hitdetails[0]['high_risk_areas']); $i++) { 
					$response .= $hitdetails[0]['high_risk_areas'][$i]."<br />";
				}
				return $response;

			case '身份证命中法院失信名单':
				$response = $hitdetails['fraud_type_display_name']."）<br />";
				return '（'.$response;

			case '身份证命中法院执行名单':
				$response = $hitdetails['fraud_type_display_name']."）<br />";
				return '（'.$response;

			case '身份证命中信贷逾期名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证命中高风险关注名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证命中车辆租赁违约名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证命中法院结案名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证_姓名命中信贷逾期模糊名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证_姓名命中法院失信模糊名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证_姓名命中法院结案模糊名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '身份证命中欠款公司法人代表名单':
				return '（'.$hitdetails['fraud_type_display_name']."）<br />";

			case '3个月内身份证关联多个申请信息':
				$response = '（';
				for ($i=0; $i < count($hitdetails[0]['frequency_detail_list']); $i++) { 
					$response .= $hitdetails[0]['frequency_detail_list'][$i]['detail']."<br />";
				}
				return $response.'）';

			case '3个月内申请信息关联多个身份证':
				$response = '（';
				for ($i=0; $i < count($hitdetails[0]['frequency_detail_list']); $i++) { 
					$response .= $hitdetails[0]['frequency_detail_list'][$i]['detail'];
				}
				return $response.'）';

			case '3个月内申请人在多个平台申请借款':
				$response = "（";
				for ($i=0; $i < count($hitdetails[0]['platform_detail_dimension']); $i++) { 
					$response .= $hitdetails[0]['platform_detail_dimension'][$i]['dimension'].'：'.$hitdetails[0]['platform_detail_dimension'][$i]['count'].'&nbsp;&nbsp;&nbsp;&nbsp;';
				}
				return $response.'）';

			default:
				return "<br />";
		}
	}

	/**
	 * 实名认证
	 * @param String $id_number 身份证号
	 * @param String $account_name	姓名
	 */
	public function realNameAuth($id_number,$account_name, $dataType=null)
	{
		// 
		if($this->bizcode!='RealnaWeb'&&!in_array('RealnaWeb', $this->bizcode)) return false;
		$fileName="UserRealnaJson/".$account_mobile.'.json';
        $postRes=ossGetObject($fileName);
        if(!$postRes){
        	$postRes = $this->vpost($this->apiurl,http_build_query([
					'biz_code'    =>'RealnaWeb',
					'id_number'   =>$id_number,
					'account_name'=>$account_name
				]),$dataType);
        	if(empty($postRes['reason_code'])){
	        	ossPutObject($fileName,json_encode($postRes,true));
	        }
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 手机号三要素
	 * @param String $account_mobile 手机号码
	 * @param String $account_name 姓名
	 * @param String $id_number 身份证号
	 */
	public function phoneEssential($account_mobile, $id_number, $account_name, $dataType=null)
	{
		if($this->bizcode!='PhthrWeb'&&!in_array('PhthrWeb', $this->bizcode)) return false;
		$fileName = "UserPhthrJson/".$account_mobile.'.json';
        $postRes = ossGetObject($fileName);
        if(!$postRes){
        	$postRes = $this->vpost($this->apiurl,http_build_query([
				'biz_code'      =>'PhthrWeb',
				'account_mobile'=>$account_mobile,
				'id_number'     =>$id_number,
				'account_name'  =>$account_name
			]),$dataType);
			if(empty($postRes['reason_code'])){
				ossPutObject($fileName,json_encode($postRes,true));
			}
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 手机号在网时长
	 * @param String $account_mobile 手机号
	 */
	public function phoneWhenlong($account_mobile, $dataType=null)
	{
		if($this->bizcode!='InnetWeb'&&!in_array('InnetWeb', $this->bizcode)) return false;
		$fileName = "UserInnetJson/".$account_mobile.'.json';
        $postRes = ossGetObject($fileName);
        if(!$postRes){
        	$postRes = $this->vpost($this->apiurl,http_build_query([
				'biz_code'      =>'InnetWeb',
				'account_mobile'=>$account_mobile,
			]),$dataType);
			if(empty($postRes['reason_code'])){
				ossPutObject($fileName,json_encode($postRes,true));
			}
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 手机号在网时长
	 * @param String $account_mobile 手机号
	 */
	public function phoneWhenlongFilter($account_mobile)
	{
		$resdata = $this->phoneWhenlong($account_mobile,'array');
		if(!empty($resdata['reason_code'])){
			return ['error'=>$resdata['reason_code'],'message'=>$resdata['reason_desc']];
		}
		if($resdata['result_desc'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['MobileDuration']){
            if($resdata['result_desc']['AUTHENTICATION_INFOQUERY']['MobileDuration']['mobile_online_time_info']){
                return ['success'=>true,'data'=>$resdata['result_desc']['AUTHENTICATION_INFOQUERY']['MobileDuration']['mobile_online_time_info']];
            }else{
            	return false;
            }
        }else{
        	return false;
        }
	}

	/**
	 * 欺诈分二点零
	 * @param String $id_number 身份证号
	 * @param String $account_mobile 手机号码
	 * @param String $event_info 事件信息
	 */
	public function fraudJudgment($id_number, $account_mobile, $event_info=false, $dataType=null)
	{
		if($this->bizcode!='FraudscWeb'&&!in_array('FraudscWeb', $this->bizcode)) return false;
		$post_data = [
			'biz_code'      =>'FraudscWeb',
			'id_number'     =>$id_number,
			'account_mobile'=>$account_mobile,
		];
		if($event_info){
			$post_data['event_info'] = $event_info;
		}
	    return  json_decode($this->vpost($this->apiurl,http_build_query($post_data),$dataType),true);
	}

	/**
	 * 家庭地址核验
	 * @param String $lend_family_address 借款人家庭地址
	 * @param String $account_mobile 手机号码
	 */
	public function homeAddressVerification($lend_family_address, $account_mobile, $dataType=null) 
	{
		if($this->bizcode!='FamaddWeb'&&!in_array('FamaddWeb', $this->bizcode)) return false;
		$fileName = "UserFamaddJson/".$account_mobile.'.json';
        $postRes = ossGetObject($fileName);
        $post_data = [
			'biz_code'=>'FamaddWeb',
			'lend_family_address'=>$lend_family_address,
			'account_mobile'=>$account_mobile,
		];
        if(!$postRes){
        	$postRes = $this->vpost($this->apiurl,http_build_query($post_data),$dataType);
        	if(empty($postRes['reason_code'])){
	        	ossPutObject($fileName,json_encode($postRes,true));
	        }
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 家庭地址核验（过滤字段）
	 * @param String $lend_family_address 借款人家庭地址
	 * @param String $account_mobile 手机号码
	 */
	public function homeAddressVerificationFilter($lend_family_address, $account_mobile)
	{
		$resdata = $this->homeAddressVerification($lend_family_address, $account_mobile, 'array');
		if(!empty($resdata['reason_code'])){
			return ['error'=>$resdata['reason_code'],'message'=>$resdata['reason_desc']];
		}
		if($resdata['result_desc'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['FamilyAddressCheck']){
			if(!isset($resdata['result_desc']['AUTHENTICATION_INFOQUERY']['FamilyAddressCheck']['home_address_consistence'])){
				$resmesdata = $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['FamilyAddressCheck']['error_info'];
			}else{
				$resmesdata = $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['FamilyAddressCheck']['home_address_consistence'];
			}
            return ['success'=>true,'data'=>$resmesdata];
        }else{
        	return false;
        }
	}

	/**
	 * 工作地址核验
	 * @param String $account_address_work 借款人单位地址
	 * @param String $account_mobile 	手机号码
	 */
	public function companyAddressVerification($account_address_work, $account_mobile, $dataType=null) 
	{
		if($this->bizcode!='EmpaddWeb'&&!in_array('EmpaddWeb', $this->bizcode)) return false;
		$fileName = "UserEmpaddJson/".$account_mobile.'.json';
        $postRes = ossGetObject($fileName);
        if(!$postRes){
        	$post_data = [
				'biz_code'            =>'EmpaddWeb',
				'account_address_work'=>$account_address_work,
				'account_mobile'      =>$account_mobile,
			];
			$postRes = $this->vpost($this->apiurl,http_build_query($post_data),$dataType);
			if(empty($postRes['reason_code'])){
				ossPutObject($fileName,json_encode($postRes,true));
			}
        }else{
        	$postRes = json_decode($postRes,true);
        }
	    return $postRes;
	}

	/**
	 * 工作地址核验
	 * @param String $account_address_work 借款人单位地址
	 * @param String $account_mobile 	手机号码
	 */
	public function companyAddressVerificationFilter($account_address_work, $account_mobile)
	{
		$resdata = $this->companyAddressVerification($account_address_work, $account_mobile, 'array');
		if(!empty($resdata['reason_code'])){
			return ['error'=>$resdata['reason_code'],'message'=>$resdata['reason_desc']];
		}
		if($resdata['result_desc'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY'] && $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['WorkAddressCheck']){
			if(!isset($resdata['result_desc']['AUTHENTICATION_INFOQUERY']['WorkAddressCheck']['work_address_consistence'])){
				$resmesdata = $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['WorkAddressCheck']['error_info'];
			}else{
				$resmesdata = $resdata['result_desc']['AUTHENTICATION_INFOQUERY']['WorkAddressCheck']['work_address_consistence'];
			}
            return ['success'=>true,'data'=>$resmesdata];
        }else{
        	return false;
        }
	}

	/**
	 * 信用分
	 * @param String $id_number 借款人身份证
	 * @param String $account_mobile 借款人手机
	 * @param String $account_name 借款人姓名
	 */
	public function creditScore($id_number, $account_mobile, $account_name, $dataType=null) 
	{
		if($this->bizcode!='CrescWeb'&&!in_array('CrescWeb', $this->bizcode)) return false;
		$post_data = [
			'biz_code'      =>'CrescWeb',
			'account_name'  =>$account_name,
			'id_number'     =>$id_number,
			'account_mobile'=>$account_mobile,
		];
	    // return $this->vpost($this->apiurl,http_build_query($post_data),$dataType);
	    return  json_decode($this->vpost($this->apiurl,http_build_query($post_data),$dataType),true);
	}

	/**
     * 模拟post获取内容函数
     */
    public function vpost($url, $data, $dataType) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

        // 5秒超时
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_HEADER, 0);

        $res = curl_exec($curl);
        if (curl_errno($curl)) {
            $res = curl_error($curl);
        }
        curl_close($curl);
        switch (strtoupper($dataType)) {
        	case 'JSON':
        	    // 返回JSON数据格式到客户端 包含状态信息
        		header('Content-Type:application/json; charset=utf-8');
                return json_encode($res);

        	case 'XML'  :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                return xml_encode($res);

            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler  =   isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                return $handler.'('.json_encode($res).');';

            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                return $res;

            case 'ARRAY':
                return json_decode($res,true);
                
        	default:
        		return $res;
        }
    }
}